if(true)then
    require("json");
else
    --引用其他json库
end
local log = io.tmpfile();
if(true)then
    log = io.stderr;
end
stdout = io.stdout;
local tmpfile = io.tmpfile();

function RPC_tmefile()
    tmpfile:seek("set");
    return tmpfile;
end

function RPC_writeOut(file)
    if(type(file)=='string')then
        local text = file;
        stdout:write("Content-Length: ",string.len(text),"\n\n"..text); --必须是 两个连续'\n'  不清楚为什么
        stdout:flush();
        return;
    end
    local n = file:seek();
    if(n>0)then
        io.stderr:write("<--Content-Length: ",n,"\n");
        file:seek("set");
        local text = file:read(n);
        io.stderr:write(text,'\n');
        io.stderr:flush();
        stdout:write("Content-Length: ",string.len(text),"\n\n"..text); --必须是 两个连续'\n'  不清楚为什么
        stdout:flush();
    end
end

function RPC_writeError(s)
    io.stderr:write(s);
    io.stderr:flush();
end

function RPC_Loop(callBack)
    while(true)do
        while(true)do
            local a = io.read("*l");
            local k,v = a:match("([^:]+):%s*(%d+)");
            log:write(a);
            log:flush();
            if(k=="Content-Length")then
                content_len = tonumber(v);
                assert(content_len,"参数应该为整数");
                break;
            end
        end

        if(content_len)then
            log:write("\n",content_len);
            local text = io.read(content_len+1);
            log:write("\n",text);
            log:flush();
            local json = parse_json(text);
            callBack(json);
        end
    end
end

